package edu.upol.paradise.hypervisor.protocol;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import edu.upol.paradise.hypervisor.NodeClusterList.NodeCluster;

public class SendCNLPacket extends ServicePacket {
	static final Logger log = Logger.getLogger(SendCNLPacket.class);
	
	public SendCNLPacket(String packetData) {
		super();
		parseData(packetData);
	}

	public SendCNLPacket() {
		super();
		setHeader(PacketHeaders.SEND_CLUSTER_NODE_LIST);
		setPacketData("");
	}
	
	private List<NodeCluster> nodes
		= new ArrayList<NodeCluster>();
	
	public void clear(){
		nodes.clear();
	}
	
	public void add(String addr, int port){
		add(new NodeCluster(addr, port));
	}
	
	public void add(NodeCluster cluster){
		nodes.add(cluster);
	}
	
	private void parseData(String packetData) {
		String[] data = packetData.split(":");
		clear();
		for (int i=0; i<data.length; i+=2){
			add(data[i], Integer.parseInt(data[i+1]));
		}
	}

	@Override
	public byte[] toBytes() throws UnsupportedEncodingException {
		StringBuilder b = new StringBuilder();
		for (NodeCluster c : nodes){
			b.append(c.addr);
			b.append(":");
			b.append(c.port);
			b.append(":");
		}
		String str = b.toString();
		str = str.substring(0, str.length()-1);
		setPacketData(str);
		return super.toBytes();
	}

	public Iterable<NodeCluster> fetchClusters() {
		return nodes;
	}
	
	
}
